package ssh

import (
	"fmt"
	"hostname-and-ssh/model"
	"hostname-and-ssh/utils"
	"os"
	"os/exec"
	"strings"
)

// SetHostname 设置主机名
func SetHostName(host *model.Host) error {
	// 执行 hostnamectl set-hostname 命令
	cmd := fmt.Sprintf("hostnamectl set-hostname %s", host.Name)
	_, err := ExecuteCommand(host, cmd)
	if err != nil {
		// 调用 LogError 记录错误日志
		utils.LogError(fmt.Errorf("failed to set hostname on %s: %w", host.Address, err))
		return fmt.Errorf("failed to set hostname on %s: %w", host.Address, err)
	}
	fmt.Printf("Successfully set hostname for %s to %s\n", host.Address, host.Name)
	return nil
}

// GenerateSSHKey 生成 SSH 密钥对
func GenerateSSHKey() error {
	// 检查~/.ssh 目录是否存在，不存在则创建
	sshDir := os.Getenv("HOME") + "/.ssh"
	if _, err := os.Stat(sshDir); os.IsNotExist(err) {
		err := os.Mkdir(sshDir, 0700)
		if err != nil {
			utils.LogError(fmt.Errorf("failed to create .ssh directory: %w", err))
			return fmt.Errorf("failed to create .ssh directory: %w", err)
		}
	}

	// 强制覆盖 id_rsa 文件
	cmd := exec.Command("ssh-keygen", "-t", "rsa", "-b", "2048", "-f", sshDir+"/id_rsa", "-N", "", "-y")
	output, err := cmd.CombinedOutput() // 捕获命令输出
	if err != nil {
		utils.LogError(fmt.Errorf("failed to generate SSH key: %w", err))
		fmt.Printf("ssh-keygen output: %s\n", string(output)) // 打印命令输出
		return fmt.Errorf("failed to generate SSH key: %w", err)
	}
	fmt.Println("SSH key pair generated successfully")
	return nil
}

// CopySSHKeyToHost 将本地的公钥复制到目标主机的 ~/.ssh/authorized_keys
func CopySSHKeyToHost(hosts *[]model.Host) error {
	// 检查 ~/.ssh/id_rsa.pub 文件是否存在
	pubKeyPath := os.Getenv("HOME") + "/.ssh/id_rsa.pub"
	if _, err := os.Stat(pubKeyPath); os.IsNotExist(err) {
		utils.LogError(fmt.Errorf("public key file does not exist: %w", err))
		return fmt.Errorf("public key file does not exist: %w", err)
	}

	// 读取本地公钥文件的内容
	pubKey, err := os.ReadFile(pubKeyPath)
	if err != nil {
		utils.LogError(fmt.Errorf("failed to read public key file: %w", err))
		return fmt.Errorf("failed to read public key file: %w", err)
	}

	// 循环将公钥复制到每台主机
	for _, host := range *hosts {
		// 使用 SSH 客户端执行命令将公钥内容追加到目标主机的 ~/.ssh/authorized_keys
		cmd := fmt.Sprintf("echo '%s' >> ~/.ssh/authorized_keys", string(pubKey))
		// 执行命令并忽略输出
		if _, err := ExecuteCommand(&host, cmd); err != nil {
			utils.LogError(fmt.Errorf("Error copying SSH key to host %s: %v", host.Address, err))
			return fmt.Errorf("failed to copy SSH key to host %s: %w", host.Address, err)
		}
		fmt.Printf("SSH key copied to %s successfully\n", host.Address)
	}
	return nil
}

// GetOSInformation 获取主机的操作系统信息
func GetOSInformation(host *model.Host) (string, string, error) {
	// 执行命令获取操作系统信息
	cmd := "cat /etc/os-release"
	output, err := ExecuteCommand(host, cmd)
	if err != nil {
		utils.LogError(fmt.Errorf("Failed to execute command '%s': %v", cmd, err))
		return "", "", fmt.Errorf("Failed to execute command '%s': %v", cmd, err)
	}

	// 解析操作系统信息
	var osName, osVersion string
	for _, line := range strings.Split(output, "\n") {
		if strings.HasPrefix(line, "ID=") {
			osName = strings.Trim(line[3:], `"`)
		}
		if strings.HasPrefix(line, "VERSION=") {
			osVersion = strings.Trim(line[8:], `"`)
		}
	}

	return osName, osVersion, nil
}

// 针对 CentOS/Red Hat 执行的配置
func ConfigureCentOS(host *model.Host) error {
	// 禁用 SELinux
	sedCmd := "sudo sed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config"
	if _, err := ExecuteCommand(host, sedCmd); err != nil {
		return err
	}

	// 清空 iptables
	iptablesFlushCmd := "sudo iptables -F"
	if _, err := ExecuteCommand(host, iptablesFlushCmd); err != nil {
		return err
	}

	// 删除 iptables 的自定义链
	iptablesDeleteCmd := "sudo iptables -X"
	_, err := ExecuteCommand(host, iptablesDeleteCmd)
	return err
}

// 针对 Ubuntu 执行的配置
func ConfigureUbuntu(host *model.Host) error {
	// 停止 ufw 防火墙
	stopCmd := []string{"sudo", "systemctl", "stop", "ufw"}
	if _, err := ExecuteCommand(host, strings.Join(stopCmd, " ")); err != nil {
		utils.LogError(fmt.Errorf("failed to stop ufw: %w", err))
		return fmt.Errorf("failed to stop ufw: %w", err)
	}

	// 禁用 ufw 防火墙
	disableCmd := []string{"sudo", "systemctl", "disable", "ufw"}
	if _, err := ExecuteCommand(host, strings.Join(disableCmd, " ")); err != nil {
		utils.LogError(fmt.Errorf("failed to disable ufw: %w", err))
		return fmt.Errorf("failed to disable ufw: %w", err)
	}

	// 返回 nil 表示配置成功
	return nil
}

// 针对 Kylin 执行的配置
func ConfigureKylin(host *model.Host) error {
	// 定义需要执行的命令列表
	commands := [][]string{
		{"sudo", "sed", "-i", "s/^SELINUX=.*/SELINUX=disabled/", "/etc/selinux/config"},
		{"sudo", "iptables", "-F"},
		{"sudo", "iptables", "-X"},
	}

	// 循环执行命令并处理错误
	for _, cmd := range commands {
		// 将命令数组拼接成字符串并执行
		if _, err := ExecuteCommand(host, strings.Join(cmd, " ")); err != nil {
			return err // 返回一个错误，停止后续命令的执行
		}
	}
	return nil // 所有命令执行成功，返回 nil
}
